package org.sith.taskrunner.ejb.db.entity;

import org.sith.taskrunner.api.user.Role;
import org.sith.taskrunner.api.user.User;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "USERS")
@NamedQueries({
        @NamedQuery(name = "updateUserActiveState",query = "update UserEntity ue set ue.active=:active where ue.id=:id"),
        @NamedQuery(name = "updateUserRole",query = "update UserEntity ue set ue.role=:role where ue.id=:id")
})
public class UserEntity implements DBEntity, User {
	
	public UserEntity(){
		
	}

	public UserEntity(String login, String password, Role role) {
		this.login = login;
		this.password = password;
		this.role = role;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(name = "LOGIN", nullable = false, unique=true)
	private String login;

	@Column(name = "PASSWORD", nullable = false)
	private String password;

	@Column(name = "ROLE", nullable = false)
	@Enumerated(EnumType.ORDINAL)
	private Role role;

	@Column(name = "IS_ACTIVE")
	private boolean active;

    @Column(name="CREATION_DATE")
    @Temporal(TemporalType.TIMESTAMP)
    private Date creationDate;

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public boolean getActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@PrePersist
	void prePersist() {
		checkIsSystemUser();
	}

	@PreUpdate
	void preUpdate() {
		checkIsSystemUser();
	}

	private void checkIsSystemUser() {
		if (Role.SYSTEM.equals(role)) {
			throw new IllegalStateException("Can't create system user");
		}
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		UserEntity that = (UserEntity) o;

		if (!login.equals(that.login))
			return false;

		return true;
	}

	@Override
	public int hashCode() {
		return login.hashCode();
	}

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
}
